<template>
  <div>
    <div id="monthLine" :style="{height:height,width:width}"/>
  </div>
</template>

<script>
import echarts from 'echarts'
import { debounce } from '@/utils'
export default {
  name: 'MonthLine',
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartMonth: {
      type: Object,
      required: true
    }
  },
  watch: {
    chartMonth: function(oldVal, newVal) {}
  },
  data() {
    return {
      chart: null,
      sidebarElm: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initMonthChart()
    })

    if (this.autoResize) {
      this.__resizeHandler = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHandler)
    }
    // 监听侧边栏的变化
    this.sidebarElm = document.getElementsByClassName('sidebar-container')[0]
    this.sidebarElm && this.sidebarElm.addEventListener('transitionend', this.sidebarMonthResizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    if (this.autoResize) {
      window.removeEventListener('resize', this.__resizeHandler)
    }

    this.sidebarElm && this.sidebarElm.removeEventListener('transitionend', this.sidebarMonthResizeHandler)

    this.chart.dispose()
    this.chart = null
  },
  methods: {
    // 全区30天内垃圾清运次数折线图
    sidebarMonthResizeHandler(e) {
      if (e.propertyName === 'width') {
        this.__resizeHandler()
      }
    },
    setMonthOptions({ xdata, data } = {}) {
      this.chart.setOption({
        color: ['#42b983'],
        title: {
          show: false,
          text: '全区30天内垃圾清运次数折线图',
          left: 'left'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          textStyle: {
            fontSize: 12
          }
        },
        grid: {
          left: '10',
          right: '20',
          bottom: '20',
          top: '30',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          data: xdata
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '清运次数',
            type: 'bar',
            areaStyle: {},
            smooth: true,
            symbol: 'none',
            animationDuration: 1000, // 加载动画显示时长
            animationEasing: 'cubicInOut',
            data: data
          }
        ]
      })
    },
    initMonthChart() {
      this.chart = echarts.init(document.getElementById('monthLine'))
      this.setMonthOptions(this.chartMonth)
    }
  }
}
</script>

<style scoped>

</style>
